package scatter.scattergenerator.rest.gen;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import scatter.common.rest.tools.ThreadContextTool;
import scatter.generator.core.BaseGenerator;
import scatter.generator.core.CustomDataSourceConfig;
import scatter.generator.core.Utils;
import scatter.generator.pojo.enums.CustomeTemplateType;
import scatter.generator.pojo.param.GenerateParam;
import scatter.scattergenerator.pojo.gen.form.GenForm;
import scatter.scattergenerator.pojo.gen.form.GenTemplateForm;
import scatter.scattergenerator.rest.config.service.IConfigDatasourceService;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * Created by yangwei
 * Created at 2021/2/24 12:23
 */
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class ScatterTableGenerator extends BaseGenerator {

    public static final String GEN_FORM_IN_THREAD_CONTEXT_KEY = "gen_form_in_thread_context_key";

    @Autowired
    private IConfigDatasourceService iConfigDatasourceService;



    @Override
    public String componentNameConvertToNoLine(String componentName) {
        return Utils.componentNameConvertToNoLine(componentName);
    }

    @Override
    public String componentNameConvertToUnderLine(String componentName) {
        return Utils.componentNameConvertToUnderLine(componentName);
    }

    @Override
    public CustomDataSourceConfig dataSourceConfig() {
        CustomDataSourceConfig config = super.dataSourceConfig();
        if (config == null) {
            GenForm genForm = (GenForm)ThreadContextTool.get(GEN_FORM_IN_THREAD_CONTEXT_KEY);
            if (genForm != null) {
                config =  iConfigDatasourceService.buildDataSourceConfigById(genForm.getTableInfo().getConfigDataSourceId());

            }

        }
        return config;
    }

    @Override
    public void doGenerate(GenerateParam param) {
        GenForm genForm = (GenForm)ThreadContextTool.get(GEN_FORM_IN_THREAD_CONTEXT_KEY);
        if (genForm != null) {
            List<CustomeTemplateType> templateTypeList = new ArrayList<>();
            for (CustomeTemplateType template : param.getTemplates()) {
                for (GenTemplateForm genTemplateForm : genForm.getTableInfo().getTemplates()) {
                    if (template.name().equals(genTemplateForm.getName()) && Optional.ofNullable(genTemplateForm.getIsGenerate()).orElse(false)) {
                        templateTypeList.add(template);
                        break;
                    }
                }
            }
            param.setTemplates(templateTypeList.toArray(new CustomeTemplateType[0]));
        }
        super.doGenerate(param);
    }
}
